package cn.yuanqiao.web.controller.system;

import cn.yuanqiao.activiti.service.ISysFileService;
import cn.yuanqiao.common.core.domain.R;

import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.system.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.pattern.PathPattern;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;

/**
 * 文件请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/file")
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     *
     * @return
     */
    @GetMapping(value = "/statics/{year}/{month}/{day}/{fileName}")
    public ResponseEntity<Resource> statics(@PathVariable("year") String year,@PathVariable("month") String month,@PathVariable("day") String day,@PathVariable("fileName") String fileName) throws UnsupportedEncodingException {
        return sysFileService.statics(year+ File.separator+month+ File.separator+day+ File.separator+fileName);
    }
}